#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef WIN32
    #include <unistd.h>
    #include <sys/time.h>
#else
    #include <time.h>
#endif

#include "lo/lo.h"
#include "MTouchware_senders.h"
#include "TuioPlayer/texttoosc.h"

#define DEFAULT_TUIO_OUT_PORT    "3333"
#define DEFAULT_TUIO_OUT_ADDRESS "127.0.0.1"

#define TABSIZE                 200

#ifdef WIN32

void usleep(long nf_time)
{
    Sleep(nf_time);
}

#endif

void usage()
{

        printf("usage : TuioPlayer [data_filename] [ipaddress] [outport#]\n");
        return;
}

int main(int argc,char *argv[])
{
    char        nf_filename[TABSIZE];
    char        nf_ipaddress[256];
    char        nf_outport[10];
    FILE        *nf_infile;
    char        nf_buffer[TABSIZE];
    char        nf_path[TABSIZE];
    lo_message  nf_lo_mess;


#ifdef WITH_TIME
    long long nf_curr, nf_prev;
    long nf_wait;
    long nf_init_prev=0;
#endif

    strcpy(nf_filename,  "../../logs/dump.tuio");
    strcpy(nf_ipaddress, DEFAULT_TUIO_OUT_ADDRESS);
    strcpy(nf_outport,   DEFAULT_TUIO_OUT_PORT);

    if((argc>4)||((argc==2)&&(strcmp(argv[1],"--help")==0)))
    {
            usage();
            return 0;
    }
    else if(argc==2)
    {
        strcpy(nf_filename,argv[1]);
    }
    else if(argc==3)
    {
       strcpy(nf_filename,  argv[1]);
       strcpy(nf_ipaddress, argv[2]);
    }
    else if(argc==4)
    {
       strcpy(nf_filename,  argv[1]);
       strcpy(nf_ipaddress, argv[2]);
       strcpy(nf_outport,   argv[3]);
    }

    nf_infile=fopen(nf_filename,"rt");

    if(!nf_infile)
    {
            printf("error while opening %s\n",nf_filename);
            exit(-1);
    }
#ifdef VERBOSE
    printf("Playing %s to %s:%s\n",nf_filename, nf_ipaddress, nf_outport);
#endif
    create_MTouchware_senders(nf_ipaddress,nf_outport);  //creating the sender

    while(!feof(nf_infile))
    {
           if( fgets(nf_buffer,TABSIZE,nf_infile))
           {
#ifdef VERBOSE
            printf("read:");
            puts(nf_buffer);
#endif
            nf_buffer[strlen(nf_buffer)-1]='\0'; // remplace le \n de fin de chaine par un '\0'

            nf_lo_mess = lo_message_new();

#ifdef WITH_TIME
            if(nf_init_prev==0)
            {
                nf_init_prev=1;
                nf_prev = getTimeFromText(nf_buffer);
            }
            else
            {
                nf_curr = getTimeFromText(nf_buffer);
                nf_wait = (nf_curr-nf_prev)/1000;
                usleep(nf_wait);
#ifdef VERBOSE
                printf("waiting %ld milliseconds\n",nf_wait);
#endif
                nf_prev = nf_curr;
            }
#endif

            text_to_osc(nf_buffer,nf_path,&nf_lo_mess);
            lo_send_message(MTouchware_senders[0],nf_path,nf_lo_mess);

            lo_message_free(nf_lo_mess);
           }
    }

    fclose(nf_infile);
	delete_MTouchware_senders();

    return 0;
}
